package config

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/md5"
	"encoding/base64"
	"strings"
)

func getKey() string {
	s2 := "b4db"
	s4 := "b3c6"
	s1 := "3565446a"
	s5 := "fa163efd2df5"
	s3 := "11e8"
	arr := []string{s1, s2, s3, s4, s5}
	return strings.Join(arr, "-")
}

func aesEncrypt(orig string) (string, error) {
	ctx := md5.New()
	ctx.Write([]byte(getKey()))
	key := ctx.Sum(nil)

	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}

	origData := []byte(orig)
	blockSize := block.BlockSize()
	origData = PKCS5Padding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	return base64.StdEncoding.EncodeToString(crypted), nil
}

func aesDecrypt(cdata string) (string, error) {
	crypted, err := base64.StdEncoding.DecodeString(cdata)
	if err != nil {
		return "", err
	}

	ctx := md5.New()
	ctx.Write([]byte(getKey()))
	key := ctx.Sum(nil)

	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5UnPadding(origData)
	return string(origData), nil
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后一个字节 unpadding 次
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
